package com.sunshine.lnuplus.view

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.adapter.PickWeeksGridViewAdapter
import com.sunshine.lnuplus.callback.CloseLessonDetailDialogCallBack
import com.sunshine.lnuplus.callback.EditLessonCallBack
import com.sunshine.lnuplus.callback.PickWeeksCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.LessonBean
import com.sunshine.lnuplus.model.room.CountDown
import com.sunshine.lnuplus.model.room.Lesson
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.UpdateWidgetUtils
import com.sunshine.lnuplus.utils.DateUtils
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.dialog_lesson_edit.*
import kotlinx.android.synthetic.main.dialog_lesson_edit.view.*
import kotlinx.android.synthetic.main.dialog_pick_color.view.*
import kotlinx.android.synthetic.main.dialog_pick_time.view.*
import kotlinx.android.synthetic.main.dialog_pick_weeks.view.*

class LessonEditDialog : DialogFragment(){

    companion object{
        private var lesson: LessonBean? = null
        private var callBack: CloseLessonDetailDialogCallBack? = null
        private lateinit var callBack1: EditLessonCallBack
        @JvmStatic
        fun newInstance(
            lesson: LessonBean?,
            dayOfWeek: Int,
            start: Int,
            end: Int,
            callBack: CloseLessonDetailDialogCallBack?,
            callBack1: EditLessonCallBack
        ) : LessonEditDialog{
            this.lesson = lesson
            this.callBack = callBack
            this.callBack1 = callBack1
            val lessonEditDialog = LessonEditDialog()
            val bundle = Bundle()
            bundle.putInt("dayOfWeek", dayOfWeek)
            bundle.putInt("start", start)
            bundle.putInt("end", end)
            lessonEditDialog.arguments = bundle
            return lessonEditDialog
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.dialog_lesson_edit, container, false)
        initView(view)
        return view
    }

    private fun initView(myView: View) {
        if(context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)){
            myView.lesson_edit_card.setCardBackgroundColor(Color.BLACK)
            myView.button_pick_time.setTextColor(Color.WHITE)
            myView.pick_weeks.setTextColor(Color.WHITE)
            myView.edit_title.setTextColor(Color.WHITE)
        }else{
            myView.lesson_edit_card.setCardBackgroundColor(Color.WHITE)
            myView.button_pick_time.setTextColor(Color.BLACK)
            myView.pick_weeks.setTextColor(Color.BLACK)
            myView.edit_title.setTextColor(Color.BLACK)
        }
        val params = dialog?.window?.attributes
        var dayOfWeek = arguments!!.getInt("dayOfWeek")
        var start = arguments!!.getInt("start")
        var end = arguments!!.getInt("end")
        var weekList: ArrayList<Int>? = if(lesson !=null) lesson!!.weeks as ArrayList<Int> else null
        var backgroundColor = if(lesson == null) "0" else lesson!!.color
        params?.apply {
            gravity = Gravity.BOTTOM
            windowAnimations = R.style.bottom_animation
        }

        //编辑保存
        myView.button_save.setOnClickListener {
            when {
                edit_lesson_name.text.toString().isEmpty() -> {
                    til_lesson_name.error = "课程名称不能为空呀~"
                    til_lesson_name.isErrorEnabled = true
                }
                edit_lesson_name.text.toString().length > 30 -> {
                    til_lesson_name.error = "课程名称过长，我可能记不住~"
                    til_lesson_name.isErrorEnabled = true
                }
                else -> {
                    til_lesson_name.isErrorEnabled = false
                    val newLessonBean: LessonBean
                    val repository = TimetableRepository(context!!)
                    if(weekList == null){
                        val defaultWeekList = ArrayList<Int>()
                        for(i in 1..InitData.lessonStyle.weekCount){
                            defaultWeekList.add(i)
                        }
                        weekList = defaultWeekList
                    }
                    if(lesson == null){
                        newLessonBean = LessonBean(
                            "${DateUtils.year}${DateUtils.month}${DateUtils.day}${DateUtils.hour}${DateUtils.minute}${DateUtils.second}",
                            edit_lesson_name.text.toString(),
                            dayOfWeek,
                            start,
                            end,
                            edit_location.text.toString(),
                            edit_teacher.text.toString(),
                            backgroundColor,
                            weekList!!
                        )
                        InitData.lessonList?.add(newLessonBean)
                        callBack1.updateView()
                        repository.insertLesson(Lesson(
                            "${DateUtils.year}${DateUtils.month}${DateUtils.day}${DateUtils.hour}${DateUtils.minute}${DateUtils.second}",
                            dayOfWeek,
                            start,
                            "",
                            end,
                            "",
                            edit_lesson_name.text.toString(),
                            edit_teacher.text.toString(),
                            edit_location.text.toString(),
                            weekList!!.toString().replace("[","").replace("]",""),
                            backgroundColor
                        ))
                        repository.insertCountDown(CountDown(
                            edit_lesson_name.text.toString(),
                            "",
                            9999,
                            9999,
                            9999,
                            9999,
                            9999,
                            "",
                            backgroundColor
                        ))
                    } else {
                        InitData.lessonList?.remove(lesson!!)
                        newLessonBean = LessonBean(
                            lesson!!.lessonId,
                            edit_lesson_name.text.toString(),
                            dayOfWeek,
                            start,
                            end,
                            edit_location.text.toString(),
                            edit_teacher.text.toString(),
                            backgroundColor,
                            weekList!!
                        )
                        InitData.lessonList?.add(newLessonBean)
                        //更改所有同名课程颜色
                        InitData.lessonList?.forEach {
                            if(it.lessonName.equals(edit_lesson_name.text.toString())){
                                it.color = backgroundColor
                            }
                        }
                        callBack1.updateView()
                        repository.updateLesson(Lesson(
                            lesson!!.lessonId,
                            dayOfWeek,
                            start,
                            "",
                            end,
                            "",
                            edit_lesson_name.text.toString(),
                            edit_teacher.text.toString(),
                            edit_location.text.toString(),
                            weekList!!.toString().replace("[","").replace("]",""),
                            backgroundColor
                        ),lesson!!.lessonName, lesson!!.dayOfWeek, lesson!!.start, lesson!!.end)
                        repository.updateBackgroundColor(lesson!!.lessonName, backgroundColor)
                        repository.updateCountDownName(lesson!!.lessonName, edit_lesson_name.text.toString())
                    }
                    UpdateWidgetUtils.updateWidgets(context!!)
                    Toasty.success(context!!, "保存成功", Toasty.LENGTH_SHORT).show()
                    dialog?.cancel()
                    callBack?.closeDialog()
                }
            }
        }

        //编辑取消
        myView.button_close.setOnClickListener{
            dialog?.cancel()
            callBack?.closeDialog()
        }

        //添加编辑
        if(lesson != null){
            myView.edit_title.text = "编辑课程"
            myView.edit_lesson_name.setText(lesson!!.lessonName)
            myView.edit_location.setText(lesson!!.location)
            myView.edit_teacher.setText(lesson!!.teacher)
            myView.pick_weeks.text = "${lesson!!.weeks}"
            myView.pick_color.setTextColor(if(backgroundColor == "0") Color.parseColor("#000000") else Color.parseColor(backgroundColor))
        }
        myView.button_pick_time.text = "周${DateUtils.getTodayOfWeekString(dayOfWeek)} 第${start}节-第${end}节"

        //选择时间按钮
        myView.button_pick_time.setOnClickListener {
            val lessonCount = InitData.lessonStyle.count
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_time, null, false)
            val lessonCountString = arrayOfNulls<String>(lessonCount)
            for(i in 1..lessonCount){
                lessonCountString[i - 1] = "第${i}节"
            }
            view.pick_week.apply {
                displayedValues = arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
                minValue = 0
                maxValue = 6
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                value = dayOfWeek - 1
            }
            view.pick_start.apply {
                displayedValues = lessonCountString
                minValue = 0
                maxValue = lessonCount - 1
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                setOnValueChangedListener { _, _, newVal ->
                    if(newVal > view.pick_end.value) view.pick_end.value = newVal
                }
                value = start - 1
            }
            view.pick_end.apply {
                displayedValues = lessonCountString
                minValue = 0
                maxValue = lessonCount - 1
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                setOnValueChangedListener { _, _, newVal ->
                    if(newVal < view.pick_start.value) view.pick_start.value = newVal
                }
                value = end - 1
            }
            val pickTime = DialogWithView.newInstance(
                view,
                "请选择上课时间",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    dayOfWeek = view.pick_week.value + 1
                    start = view.pick_start.value + 1
                    end = view.pick_end.value + 1
                    myView.button_pick_time.text = "周${DateUtils.getTodayOfWeekString(dayOfWeek)} 第${start}节-第${end}节"
                },
                null)
            pickTime.show(childFragmentManager, "pickTime")
        }

        //选择周数
        myView.pick_weeks.setOnClickListener {
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_weeks, null, false)
            var tempWeekList = ArrayList<Int>()
            val callBack = object : PickWeeksCallBack {
                override fun callBack(weekList: List<Int>) {
                    tempWeekList = weekList as ArrayList<Int>
                }
            }
            view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(context!!, weekList, callBack)
            val pickWeek = DialogWithView.newInstance(
                view,
                "请选择上课周数",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    weekList = tempWeekList
                    myView.pick_weeks.text = "$weekList"
                },
                null)
            pickWeek.show(childFragmentManager, "pickWeek")
            view.all_week.setOnClickListener {
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(context!!, null, callBack)
            }
            view.dan_week.setOnClickListener {
                val danWeekList = ArrayList<Int>()
                for(i in 1..InitData.lessonStyle.weekCount){
                    if(i % 2 != 0){
                        danWeekList.add(i)
                    }
                }
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(
                    context!!,
                    danWeekList,
                    callBack
                )
            }
            view.shuang_week.setOnClickListener {
                val shuangWeekList = ArrayList<Int>()
                for(i in 1..InitData.lessonStyle.weekCount){
                    if(i % 2 == 0){
                        shuangWeekList.add(i)
                    }
                }
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(
                    context!!,
                    shuangWeekList,
                    callBack
                )
            }
        }

        //选择背景颜色
        myView.pick_color.setOnClickListener {
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
            var tempColor = "#ff0000"
            val pickColor = DialogWithView.newInstance(
                view,
                "请选择课程背景颜色",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    backgroundColor = tempColor
                    myView.pick_color.setTextColor(if(backgroundColor == "0") Color.parseColor("#000000") else Color.parseColor(backgroundColor))
                },
                null)
            pickColor.show(childFragmentManager, "pickColor")
            view.color_pick_view.setOnColorChangeListener {
                tempColor = String.format("%08x",it)
                tempColor = "#" + tempColor.substring(2, tempColor.length)
            }
            view.button_color_default.setOnClickListener {
                backgroundColor = "0"
                myView.pick_color.setTextColor(Color.parseColor("#000000"))
                pickColor.dismiss()
            }
        }
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(activity!!.windowManager.defaultDisplay.width,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }

}
